package com.imooc.imoocbilibili.task;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.imooc.imoocbilibili.entity.UserFollowing;
import com.imooc.imoocbilibili.entity.UserMoments;
import com.imooc.imoocbilibili.service.UserFollowingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 江黎
 * @since 2022-04-16
 */
@Component
@Slf4j
public class UserMomentsTask {

    @Autowired
    private UserFollowingService userFollowingService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Async("AsyncTaskExecutor")
    public void pushUserMomentsTaskToFans(UserMoments userMoments) {
        // 给粉丝发送动态
        List<UserFollowing> userFans = userFollowingService.getUserFans();
        if (CollectionUtil.isNotEmpty(userFans)) {
            for (UserFollowing userFan : userFans) {
                Long fanUserId = userFan.getUserid();
                String key = "subscribed-" + fanUserId;
                String subscribedListStr = redisTemplate.opsForValue().get(key);
                List<UserMoments> subscribedList;
                if (StrUtil.isBlank(subscribedListStr)) {
                    subscribedList = new ArrayList<>();
                } else {
                    subscribedList = JSONUtil.toList(subscribedListStr, UserMoments.class);
                }
                subscribedList.add(userMoments);
                redisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(subscribedList));
            }
        }
    }
}
